/**
 * InheritanceTree.java
 * @author: liuex
 * 2008-1-14 ����02:07:49
 *
 * note: 
 */
package org.lex.reflect.browsing.view.browser;

import java.awt.Component;

import javax.swing.Icon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

import org.lex.reflect.browsing.util.ClassHelper;
import org.lex.reflect.browsing.util.IconCache;
import org.lex.swing.Swings;


public class InheritanceTree extends JTree {
	public enum Type {
		INHERITANCE, SUPER_TYPE
	};

	private Type viewType = Type.INHERITANCE;
	private Class<?> clazz = null;
	private DefaultTreeModel model = null;

	public InheritanceTree() {
		this.model = new DefaultTreeModel(new DefaultMutableTreeNode(this.getClass()), true);
		this.setCellRenderer(new DefaultTreeCellRenderer() {
			private Icon classIcon = IconCache.getIcon(IconCache.CLASS);
			private Icon interfaceIcon = IconCache.getIcon(IconCache.INTERFACE);
			private Icon enumIcon = IconCache.getIcon(IconCache.ENUM);

			public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
					boolean leaf, int row, boolean hasFocus) {
				super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
				Object v = ((DefaultMutableTreeNode) value).getUserObject();
				if (v instanceof Class) {
					Class<?> clazz = (Class<?>) v;
					this.setIcon(this.getIcon(clazz));
					this.setText(ClassHelper.getTypeName(clazz));
				}
				return this;
			}

			private Icon getIcon(Class<?> clazz) {
				if (clazz.isInterface())
					return interfaceIcon;
				if (clazz.isEnum())
					return enumIcon;
				return classIcon;
			}
		});
		this.setClass(null);
	}

	public void setClass(Class<?> clazz) {
		this.clazz = clazz;
		if (clazz == null) {
			this.setModel(null);
			return;
		}
		TreeNode root = null;
		switch (viewType) {
		case INHERITANCE:
			root = ClassHelper.createInheritanceRootNode(clazz);
			break;
		case SUPER_TYPE:
			root = ClassHelper.createSuperTypeRootNode(clazz);
			break;
		default:
			throw new IllegalArgumentException(viewType.toString());
		}
		this.model.setRoot(root);
		this.setModel(model);
		Swings.expandAll(this);
	}

	public void setViewType(Type type) {
		this.viewType = type;
		this.setClass(clazz);
	}
}
